<template>
  <div id="play-detail" class="content-box mtop-20">
    <!-- 顶部歌单信息 -->
    <TopInfo
      tagName="歌单"
      :playList="playList"
      @goUserDetail="goUserDetail"
    >
      <!-- 图片 -->
      <template #picture>
        <img
          class="img-percent"
          v-if="isList"
          v-lazy="`${playList.coverImgUrl}?param=300y300`"
        >
      </template>
      <!-- 按钮 -->
      <template #btns>
        <a-button
          class="br-30 play-all"
          type="danger"
          @click="playAll"
        >
          <a-icon class="font-16" type="caret-right" />播放全部
        </a-button>
        <a-button
          class="mright-10 br-30 play-add"
          type="danger"
          @click="addMore"
        >
          <a-icon class="font-16" type="plus" />
        </a-button>
        <a-button
          v-if="isList"
          class="mright-10 br-30"
           @click="changeSubscribe"
        >
          <a-icon
            class="font-16"
            :type="subscribed ? 'check' : 'folder-add'"
          />
          {{ subscribed ? '已收藏' : '收藏' }}({{ subscribedCount }})
        </a-button>
        <a-button class="br-30">
          <a-icon class="font-16" type="logout" style="transform: rotate(-45deg);" />
          分享({{ shareCount }})
        </a-button>
      </template>
      <!-- 标签 -->
      <template>
        <div v-if="isList && playList.tags.length" class="font-16">
          <span>标签：{{ playList.tags.join(' ') }}</span>
        </div>
        <div v-if="isList" class="font-16">
          <span>歌曲：{{ playList.trackCount }} 首</span>
          <span class="mleft-20">播放：{{ playCount }}</span>
        </div>
      </template>
    </TopInfo>
    <!-- 搜索框和导航栏 -->
    <Tab :tabList="tabList" :loading="loading" @target="target">
      <template #other>
        <a-input-search
          placeholder="搜索音乐"
          style="width: 200px"
          @search="onSearch"
        />
      </template>
    </Tab>
    <!-- 这里都改成v-if,v-show显示隐藏时,DOM已经全部渲染完毕了,导致进入就会Collectors组件中的scrollMore, -->
    <MyList
      ref="myList"
      v-if="showModule === 'songList'"
      :columns="columns"
      :dataSource="dataSource"
    >
      <template #more>
        <LoadMore ref="loadMore" :more="more" @scrollMore="scrollByList" />
      </template>
    </MyList>
    <Discuss
      ref="discuss"
      :newTotal="songsTotal"
      :newComments="songsComments"
      v-else-if="showModule === 'comments'"
      @scrollTo.passive="scroll"
    />
    <Collectors
      ref="collectors"
      v-else
    />

    <!-- 播放全部提示框 -->
    <a-modal
      :visible="visibleLogout"
      @onOk="onOk"
      @onCancel="cancel"
    >
      <template #title>
        <span>替换播放列表</span>
      </template>
      <template #content>
        <!-- <div class="content"> -->
        <div style="margin: 20px;">"播放全部"将会替换当前的播放列表,是否继续?</div>
        <!-- <a-checkbox @change="onChange">
          不再提醒
        </a-checkbox> -->
        <!-- </div> -->
      </template>
    </a-modal>

    <!-- 返回顶部 -->
    <w-go-top :target="getDOM" />
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { Input } from 'ant-design-vue';
import { morePlayDetail, subList } from '@/api';
import { songsComments } from '@/api/detail';
import { changeBigCount } from '@/utils/figure';
import Collectors from './collectors';
import Discuss from '@/components/Detail/Discuss';
import GoTop from '@/components/Library/GoTop';
import List from '@/components/Detail/List';
import Tab from '@/components/Content/Tabs';
import TopInfo from '@/components/Detail/TopInfo';
// 加载更多组件
import LoadMore from '@/components/Library/LoadingMore';
import Modal from '@/components/Library/Modal';

export default {
  name: 'playDetail',

  components: {
    Tab,
    TopInfo,
    Discuss,
    LoadMore,
    Collectors,
    AModal: Modal,
    MyList: List,
    WGoTop: GoTop,
    AInputSearch: Input.Search
  },

  data() {
    return {
      tabList: [{
        tabName: '歌曲列表',
        isActive: true,
        id: 'songList'
      }, {
        tabName: `评论()`,
        isActive: false,
        id: 'comments'
      }, {
        tabName: '收藏者',
        isActive: false,
        id: 'collectors'
      }],
      dataSource: [],
      columns: [
        {
          title: '',
          dataIndex: 'index',
          key: 'index',
          width: 50,
          scopedSlots: { customRender: 'key' }
        },
        {
          title: '',
          dataIndex: 'operation',
          key: 'operation',
          width: 30,
          scopedSlots: { customRender: 'operation' }
        },
        {
          title: '音乐标题',
          dataIndex: 'name',
          key: 'name',
          ellipsis: true,
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '歌手',
          dataIndex: 'ar',
          key: 'ar',
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: 'ar' }
        },
        {
          title: '专辑名',
          dataIndex: 'al',
          key: 'al',
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: 'al' }
        },
        {
          title: '时长',
          dataIndex: 'duration',
          key: 'duration',
          ellipsis: true,
          width: 80,
          scopedSlots: { customRender: 'duration' }
        },
      ],
      // 歌单评论参数
      params: {
        id: this.$route.query.id,
        limit: 20,
        offset: 0,
        // before: 0,
        timestamp: new Date().getTime()
      },
      // 歌单评论
      songsComments: [],
      // 歌单评论总数
      songsTotal: 0,
      showModule: 'songList',
      more: true,
      // 是否已收藏
      subscribed: false,
      // 显示隐藏弹框
      visibleLogout: false
    };
    
  },

  watch: {
    // 监听路由变化,需要调用接口
    '$route.query.id': {
      handler(value) {
        // const id = this.$route.query.id;
        this.$store.dispatch('main/getPlayDetail', value);
        this.$store.commit('main/LOADING', true);
        // 播放根据这个值进行判断
        // this.$store.commit('main/ISPLAYED', false);
      },
      immediate: true
    },
    playList: {
      handler(value) {
        if (value && value.tracks && value.tracks.length) {
          if (value.trackIds.length === value.tracks.length) {
            this.$nextTick(() => this.more = false);
          }
          this.tabList[1].tabName = `评论(${value.commentCount})`;
          this.dataSource = value.tracks;
          this.subscribed = value.subscribed;
        }
      },
      immediate: true
    }
  },

  computed: {
    ...mapState({
      playList: state => state.main.playList,
      loading: state => state.main.loading,
      userInfo: state => state.detail.userInfo
    }),
    getDiscuss() {
      return this.$refs.discuss;
    },
    isList() {
      return this.playList && Object.keys(this.playList).length;
    },
    canSub() {
      const user = JSON.parse(localStorage.getItem('userInfo'));
      if (user) {
        return this.playList.userId === user.userId;
      }
      return '';
    },
    subscribedCount() {
      return changeBigCount(this.playList.subscribedCount);
    },
    shareCount() {
      return changeBigCount(this.playList.shareCount);
    },
    playCount() {
      return changeBigCount(this.playList.playCount);
    },
  },

  methods: {
    getDOM() {
      return document.querySelector('#play-detail');
    },
    // tab切换时的动作
    target(value) {
      switch(value) {
        // 使用v-if进行显示隐藏,所以需要nextTick，等待DOM渲染完毕才能获取到refs
        case 'songList':
          // 需要进行判断数据的长度是否大于10,如果大于10就不再显示加载中
          // this.$nextTick(() => {
          //   if (this.dataSource.length > 10) {
          //     this.$refs.loadMore.more = false;
          //   }
          // })
          break;
        case 'comments':
          this.$nextTick(() => {
            this.getDiscuss.params.type = 2;
            this.getDiscuss.params.id = this.$route.query.id;
            this.getDiscuss.getHotComments();
            this.getSongsComments();
          });
          break;
      }
      this.showModule = value;
    },
    // 获取歌单评论
    async getSongsComments() {
      const all = (await songsComments(this.params)).data;
      this.songsComments = Object.freeze(all.comments);
      this.songsTotal = Object.freeze(all.total);
    },
    // 监听是否滚动到底部
    async scrollByList() {
      if (this.isList) {
        // const otherids = this.playList.trackIds.slice();
        // 获取需要再次加载的歌曲id
        const idsArr = this.playList.trackIds.map(item => item.id);
        // 调用加载更多歌曲接口
        if (idsArr && idsArr.length) {
          const songs = (await morePlayDetail(idsArr.join())).data;
          this.dataSource = songs.songs;
          // this.$refs.loadMore.more = false;
          this.more = false;
        }
      }
    },
    async changeSubscribe() {
      if (this.canSub) {
        this.$message.error('不能收藏自己的歌单');
        return;
      }
      this.subscribed = !this.subscribed;
      const res = (await subList({
        t: this.subscribed ? 1 : 2,
        id: this.playList.id,
        timestamp: new Date().getTime()
      })).data;
      if (res.code === 200) {
        if (this.subscribed) {
          this.$message.success('收藏成功');
        } else {
          this.$message.success('取消收藏成功');
        }
        // 重新调用收藏歌单接口更新列表
        this.$store.dispatch('detail/getPlayListU', {
          uid: this.userInfo.userId,
          timestamp: new Date().getTime()
        });
      }
    },
    // 点击分页后，滚动回最新评论标题处
    scroll(current) {
      this.params.offset = (current - 1) * this.params.limit;
      this.getSongsComments();
      const detail = document.querySelector('#play-detail');
      const lastDOM = this.$refs.discuss.$el.childNodes;
      detail.scrollTo({
        left: 0,
        top: lastDOM[lastDOM.length - 1].lastChild.offsetTop - 95,
        behavior: 'smooth'
      })
    },
    // 播放全部
    playAll() {
      this.visibleLogout = true;
    },
    onOk() {
      this.visibleLogout = false;
      this.$store.commit('main/ISPLAYED', true);
      // 播放第一首
      this.$store.commit('detail/AUDIOID', this.dataSource[0]);
      this.$store.commit('detail/AUDIOLIST', this.dataSource);
    },
    cancel() {
      this.visibleLogout = false;
    },
    // 添加到播放列表
    addMore() {
      this.$store.commit('detail/ADDAUDIOLIST', this.dataSource);
      this.$message.success('已添加到播放列表')
    },
    onChange(e) {
      this.isModal = e.target.checked;
    },
    // 跳转至用户详情
    goUserDetail(id) {
      this.$router.push({
        name: 'userdetail',
        query: { id }
      })
    },
    onSearch() {}
  }
};
</script>

<style lang="less" scoped>
#play-detail {
  height: calc(100% - 20px) !important;
  /deep/ul.tab-list {
    margin-left: 0 !important;
  }
  /deep/input.ant-input {
    border-radius: 30px;
    box-shadow: none;
    &:focus,
    &:hover {
      border-color: #ff4d4f;
      box-shadow: 0 2px 0 rgb(0 0 0 / 5%);
    }
  }
  .play-all {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }
  .play-add {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    border-left: 1px solid #fff;
  }
}
</style>